package com.exadt.java;

//import com.luciad.imageio.webp.WebPWriteParam;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@SpringBootApplication
@RestController
public class ImageioApplication {

    public static void main(String[] args) {

        SpringApplication.run(ImageioApplication.class, args);
    }

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {

        System.out.println("Hello World!");
//        String srcFile = System.getProperty("user.dir") + "/file/Input/" + "Input.png"; //原图地址
//        String webpFile = System.getProperty("user.dir") + "/file/Output/" + "Output.png"; //输出地址
//        encodingToWebp(srcFile, webpFile);
//
//
//        Thumbnails.of(new File("path/to/directory").listFiles())
//                .size(640, 480)
//                .outputFormat("jpg")
//                .toFiles(Rename.PREFIX_DOT_THUMBNAIL);


        return String.format("Hello %s!", name);
    }

    @GetMapping("/imageio/index.html")
    public String index() {
//        ModelAndView mv = new ModelAndView();
//        mv.addObject("user", "ook");
//        mv.setViewName("hello.html");
        return "hello";
    }

    @PostMapping("/imageio/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file,
                         String format,
                         String compression,
                         String scale, HttpServletResponse response) {
        if (file.isEmpty()) {
            return "{\"code\":1,\"msg\":\"上传失败，请选择文件\"}";
        }

//        String srcfile = "asfasdfasdf/sfasdf.png";
        // <option value="None" >保存原格式</option>
        //                    <option value="PNG">PNG</option>
        //                    <option value="JPG">JPG</option>
        //                    <option value="WEBP">WEBP</option>
        //                    <option value="BMP">BMP</option>
//        String format = "WEBP";//,None,PNG,JPG,WEBP,BMP
//        String thumfile = "srandi.png";
//        String thumfilepath = getOutFileName(new File(thumfile), format);
//        mkDirs(thumfilepath);
//        double scale = 1.0;
//        double compression = 0.5;

//        if (exaName.toLowerCase() != "webp" && format.toLowerCase() == "webp") {
//            encodingToWebp(srcf, new File(thumfilepath));
//        } else {
//            save(srcfile, thumfilepath, format, scale, compression);
//        }

//        String fileName = file.getOriginalFilename();
//        String filePath = System.getProperty("user.dir") + "/uploadfile/temp-" + file.getOriginalFilename();
        Double dscale = new Double(scale);
        Double dcompression = new Double(compression);
        System.out.println(format + ":" + scale + ":" + compression + ">>" + file.getOriginalFilename());
//        File odesc = new File(filePath);
//        mkDirs(filePath);
        try {
            ServletOutputStream servletOutputStream= response.getOutputStream();
//            file.transferTo(odesc);
//            String thumfilepath = getOutFileName(odesc, format);
//            mkDirs(System.getProperty("user.dir") + thumfilepath);
            response.setContentType("application/octet-stream");
            String outfile="out_"+ URLEncoder.encode(file.getOriginalFilename(),"utf-8");
            if(format!=null&&!format.toLowerCase().equals("none")) {
                outfile = outfile + "." + format.toLowerCase();
            }
            response.setHeader("Content-Disposition","attachment;fileName="+outfile);
          InputStream inputStream= file.getInputStream();
                save(inputStream,servletOutputStream,format,dscale,dcompression);
            inputStream.close();
            servletOutputStream.close();
                return null;
//            save(odesc.getPath(), System.getProperty("user.dir") + thumfilepath, format, dscale, dcompression);
//            if (odesc.delete()) {
//                System.out.println("delete id ok :" + odesc.getAbsoluteFile());
//            } else {
//                System.out.println("delete id error :" + odesc.getAbsoluteFile());
//            }
            //return "{\"code\":0,\"msg\":\"上传成功\",\"data\":\"" + thumfilepath + "\"}";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{\"code\":1,\"msg\":\"上传失败\"}";
    }

    private  static  void save(InputStream inputStream, OutputStream outputStream, String format, double scale, double compression){
        try {
            switch (format){
                case "JPG":
                    Thumbnails.of(inputStream).scale(scale)
                            .addFilter(new ThumbnailsImgFilter())
                            .outputFormat("jpg")
                            .outputQuality(compression)
                            .toOutputStream(outputStream);
                    break;
                case "PNG":
                    Thumbnails.of(inputStream).scale(scale)
                            .outputFormat("png")
                            .outputQuality(compression)
                            .toOutputStream(outputStream);
                    break;
                case "WEBP":
                    Thumbnails.of(inputStream).scale(scale)
                            .imageType(ThumbnailParameter.DEFAULT_IMAGE_TYPE)
                            .outputFormat("webp")
                            .outputQuality(compression)
                            .toOutputStream(outputStream);
                    break;
                case "BMP":
                    Thumbnails.of(inputStream).scale(scale)
                            .addFilter(new ThumbnailsImgFilter())
                            .outputFormat("bmp")
                            .outputQuality(compression)
                            .toOutputStream(outputStream);
                    break;
                default:
                    Thumbnails.of(inputStream).scale(scale)
                            .imageType(ThumbnailParameter.DEFAULT_IMAGE_TYPE)
                            .outputQuality(compression)
                            .toOutputStream(outputStream);
                    break;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 转码图片
    private  static  void save(String originalImage,String thumbnailImage,String format,double scale,double compression){
        try {
            switch (format){
                case "JPG":
                    Thumbnails.of(originalImage).scale(scale)
                            .addFilter(new ThumbnailsImgFilter())
                            .outputFormat("jpg")
                            .outputQuality(compression)
                            .toFile(thumbnailImage);
                    break;
                case "PNG":
                    Thumbnails.of(originalImage).scale(scale)
                            .outputFormat("png")
                            .outputQuality(compression)
                            .toFile(thumbnailImage);
                    break;
                case "WEBP":
                    Thumbnails.of(originalImage).scale(scale)
                            .imageType(ThumbnailParameter.DEFAULT_IMAGE_TYPE)
                            .outputFormat("webp")
                            .outputQuality(compression)
                            .toFile(thumbnailImage);
                    break;
                case "BMP":
                    Thumbnails.of(originalImage).scale(scale)
                            .addFilter(new ThumbnailsImgFilter())
                            .outputFormat("bmp")
                            .outputQuality(compression)
                            .toFile(thumbnailImage);
                    break;
                default:
                    Thumbnails.of(originalImage).scale(scale)
                            .imageType(ThumbnailParameter.DEFAULT_IMAGE_TYPE)
                            .outputQuality(compression)
                            .toFile(thumbnailImage);
                    break;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private  static  void mkDirs(String thumbnailImagePath) {
        File thumbnailImage = new File(thumbnailImagePath);
        // 判断路径是否存在，如果不存在则创建
        if (!thumbnailImage.getParentFile().exists()) {
            thumbnailImage.getParentFile().mkdirs();
        }
    }


    private static String getOutFileName (File originalImage ,String format) {
        String thumbnailImageName = originalImage.getName(); //缩略图输出名
        String thumbnailImagePath; //缩略图输出地址
        switch (format) {
            case "JPG":
                thumbnailImagePath = "/static/"
                        + thumbnailImageName.substring(0, thumbnailImageName.lastIndexOf(".")) + ".jpg";
                break;
            case "PNG":
                thumbnailImagePath = "/static/"
                        + thumbnailImageName.substring(0, thumbnailImageName.lastIndexOf(".")) + ".png";
                break;
            case "WEBP":
                thumbnailImagePath = "/static/"
                        + thumbnailImageName.substring(0, thumbnailImageName.lastIndexOf(".")) + ".webp";
                break;
            case "BMP":
                thumbnailImagePath = "/static/"
                        + thumbnailImageName.substring(0, thumbnailImageName.lastIndexOf(".")) + ".bmp";
                break;
            default:
                thumbnailImagePath = "/static/" + thumbnailImageName;
                break;
        }
        return thumbnailImagePath;
    }


//    private static void encodingToWebp(String srcFile, String webpFile) {
//        encodingToWebp(new File(srcFile), new File(webpFile));
//    }
//
//    /**
//     * @param: srcFile
//     * @param: webpFile
//     * @description: 将文件编码为WEBP格式
//     * @author: Mintimate
//     */
//    private static void encodingToWebp(File srcFile, File webpFile) {
//
//        try {
//
//            // Obtain an image to encode from somewhere
//            BufferedImage image = ImageIO.read(srcFile);
//
//            // Obtain a WebP ImageWriter instance
//            ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
//
//            // Configure encoding parameters
//            WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
//            writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
//            writeParam.setCompressionType(writeParam.getCompressionTypes()[WebPWriteParam.LOSSLESS_COMPRESSION]);
//
//            FileImageOutputStream fileImageOutputStream = new FileImageOutputStream(webpFile);
//            // Configure the output on the ImageWriter
//            writer.setOutput(fileImageOutputStream);
//            // Encode
//            writer.write(null, new IIOImage(image, null, null), writeParam);
//
//            //释放reader
//            writer.dispose();
//
//            //关闭文件流
//            fileImageOutputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
